package controller

import (
	"dsc-server/domain/dto"
	"dsc-server/pkg/service"
	"github.com/liangboceo/yuanboot/utils/jwt"
	"net/http"
	"strconv"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// UserController 用户控制器
type UserController struct {
	BaseController
	DB          *gorm.DB
	UserService *service.UserService
	JwtSecret   string // JWT密钥
}

// NewUserController 创建UserController实例
func NewUserController(db *gorm.DB) *UserController {
	return &UserController{
		DB:          db,
		UserService: service.NewUserService(db),
		JwtSecret:   "your-jwt-secret", // 实际应用中应从配置文件读取
	}
}

// Login 用户登录
func (ctrl *UserController) Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "用户名或密码不能为空"))
		return
	}

	user, err := ctrl.UserService.GetUser(username, password)
	if err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "用户名或密码错误"))
		return
	}

	// 生成JWT Token
	token, err := ctrl.createToken(strconv.FormatUint(uint64(user.ID), 10), user.Password)
	if err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "生成Token失败"))
		return
	}

	c.JSON(http.StatusOK, dto.Success(token))
}

// ResetPassword 重置密码
func (ctrl *UserController) ResetPassword(c *gin.Context) {
	password := c.PostForm("password")
	if password == "" {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "密码不能为空"))
		return
	}

	result := ctrl.UserService.ResetPassword(password)
	c.JSON(http.StatusOK, result)
}

// createToken 创建JWT Token
func (ctrl *UserController) createToken(userId string, password string) (string, error) {
	// 创建JWT声明
	claims := jwt.MapClaims{
		"userId":   userId,
		"password": password,
		"exp":      time.Now().Add(time.Hour * 24).Unix(), // 24小时过期
	}

	// 创建Token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// 签名Token
	return token.SignedString([]byte(ctrl.JwtSecret))
}
